import React, {useMemo, useRef} from "react";
import {Badge} from "antd";

import SkProTable, {TableType, IProTableRef} from "vendor/components/pro-table-native";
import {helper} from "vendor/utils/T";
import {EnumAuthKey, permission} from "@/service/permission";
import { useThemeToken } from "@/constants";
import {EnumStatus} from '../../../../constants'

import {getDataAction, filterItems} from './proTableDriver';
import {RespDataType} from '../api';

const List: React.FC = () => {
    const { themeToken } = useThemeToken();
    const proTableRef = useRef<IProTableRef>();
    const columns = useMemo(() => getColumns(), []);

    return (
        <SkProTable
            ref={proTableRef}
            dataAction={getDataAction(proTableRef)}
            rowKey={"infoId"}
            theme={themeToken.proTableToken}
            headerProps={{
                operatorProps: {
                    btnList: [
                        {innerType: "delete", authKey: EnumAuthKey.loginlog.removeButton}
                    ].filter((item) => permission.can(item.authKey)),
                },
                filterProps: {
                    maxWidth: "60%",
                    filterItems
                }
            }}
            contentProps={{
                tableProps: {
                    columns,
                }
            }}
            onError={(msg) => console.error(msg)}
        />
    )
}

export default List;

const getColumns = () => {
    const statusToInfo = helper.convertArrayToObj(EnumStatus);

    const columns: TableType.ColumnsType<RespDataType.LoginLogItem> = [
        {
            title: '序号',
            dataIndex: 'infoId',
        },
        {
            title: '用户名称',
            dataIndex: 'userName',
        },
        {
            title: '登录IP地址',
            dataIndex: 'ipaddr',
        },
        {
            title: '登录地点',
            dataIndex: 'loginLocation',
        },
        {
            title: '浏览器',
            dataIndex: 'browser',
        },
        {
            title: '操作系统',
            dataIndex: 'os',
        },
        {
            title: '状态',
            dataIndex: 'status',
            render: (value) => {
                const {label, color} = statusToInfo[value];
                return <span>
                    <Badge color={color}/>
                    <span style={{color}}>{label}</span>
                </span>
            }
        },
        {
            title: '提示消息',
            dataIndex: 'msg',
        },
        {
            title: '访问时间',
            dataIndex: 'loginTime',
        },
    ];

    return columns;
}